<?php
namespace app\admin\controller;
use app\service\roominfoService;
use app\service\xcxService;
use think\facade\Db;
use think\facade\View;

ini_set('max_execution_time','0');
class Car extends Common{
    //下拉菜单
    public function fetchdata() {
        $type = request()->post('type');
        switch($type) {
            case 1:
                $community_id = request()->post('community_id');
                $group = array_unique((new roominfoService())->groupList($community_id));
                $group = array_filter($group);
                return array_values($group);
            case 2:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = array_unique((new roominfoService())->buildingList($community_id,$group));
                sort($building);
                return $building;
            case 3:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = array_unique((new roominfoService())->unitList($community_id,$group,$building));
                sort($unit);
                return $unit;
            case 4:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = request()->post('unit');
                $room = array_unique((new roominfoService())->roomList($community_id,$group,$building,$unit));
                sort($room);
                return $room;
            case 5:
                $com = $this->pidTokenId();
                $whe['community_id'] = array('in',$com['community_id']);//所有小区ID
                $community_name = request()->post('community_name');
                return Db::name('community')
                        ->where('community_name','like','%'.$community_name.'%')
                        ->where($whe)
                        ->field('community_id,community_name')
                        ->select()->toArray();
            default:
                return json(['info' => '查询错误']);
        }
    }
   
    //显示小区房屋信息
    public function carList(){
        //查询小区信息
        $com = $this->pidTokenId();

        $whe[] =['community_id','in',$com['community_id']];//所有小区ID
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        View::assign('communitylist',$communitylist);

		$str="[";
		foreach ($communitylist as $key => $value) {
			$str=$str."'".$value["community_name"]."',";
		}
		$str=$str."]";
		
		View::assign("str",$str);
        //查询
        $data = request()->get();
       
        if (!empty($data)){
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];//小区名称
            }else{
                $where['community_id'] = "";
            }
            
            if(!empty($data['group'])){
                $where['group'] = $data['group'];//组团
            }else{
                $where['group'] = "";
            }
            if(!empty($data['building'])){
                $where['building'] = $data['building'];//楼栋
            }else{
                $where['building'] = "";
            }
            if(!empty($data['address'])){
                $where['address'] = array("like","%".$data['address']."%");//楼栋
            }else{
                $where['address'] = "";
            }
            if(!empty($data['unit'])){
                $where['unit'] = $data['unit'];//单元
            }else{
                $where['unit'] = "";
            }
            if(!empty($data['room'])){
                $where['room'] = $data['room'];//房号
            }else{
                $where['room'] = "";
            }
            if(!empty($data['owner_name'])){
                $where['owner_name'] = $data['owner_name'];//姓名
            }else{
                $where['owner_name'] = "";
            }
            if(!empty($data['owner_phone'])){
                $where['owner_phone'] = $data['owner_phone'];//电话
            }else{
                $where['owner_phone'] = "";
            }
            if(!empty($data['status'])){
                $where['status'] = $data['status'];//状态
            }else{
                $where['status'] = "";
            }
            View::assign('where',$where);   
            $where = array_filter($where);
        }else{
            $where = null;
        }
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);
        $page = request()->has('page') ? request()->get('page') : 1;
        //查询房屋条数
       
        $number =Db::name('carspace')->where('community_id','in',$community_id)->where($where)->count();;
        View::assign('number',$number);
        //查询车位信息
    
        $carlist=Db::name('carspace')->where('community_id','in',$community_id)->where($where)->order('id desc')->paginate(200, false, [
            'page'  =>  $page,
            'query' =>  $where
        ]);
        //判断是否有数据
        if(!empty($number)){
            foreach($carlist as $room){
                
                //根据小区编号查询小区名称
                $room['community_id'] = (new roominfoService())->communityName($room['community_id']);
                //数据从新存入数组
                $list[] = $room;
                View::assign('list',$list);
            }
        }else{
            View::assign('list',$carlist);
        }
        //View::assign('list',$roomlist);
        View::assign('roomlist',$carlist);
       
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
       
        return View::fetch('car_list');
    }

   

    //车位添加
    public function carAdd(){
        //查询小区信息
        $com = $this->pidTokenId();
        $where['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($where);
        View::assign('communitylist',$communitylist);

        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
            //房屋完整门牌
            $data['address'] = $data['group']."-".$data['building']."-".$data['unit']."-".$data['room'];
            
            $data['time'] = date('Y-m-d H:i:s',time());//添加时间
            
            
            //将数据插入数据库
            $result = Db::table("carspace")->insert($data);
            //判断数据是否插入成功
            if($result){
                return "添加车位成功";
                $this->success('添加车位成功',url('carlist'));
            }else{
                $this->error('添加车位失败',url('carAdd'));
            }
        }else{
            return View::fetch('car_add');
        }
    }

    //修改车位信息
    public function carEdit(){
        //查询小区信息
        $com = $this->pidTokenId();
        $where['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($where);
        View::assign('communitylist',$communitylist);
        
        if(request()->isGet()){
            if(!request()->has('id') || empty(request()->param('id'))){
                $this->error('房屋ID错误');
            }
            $id = request()->param('id');
            //查询车位数据
            $info = Db::table("carspace")->where("id",$id)->find();
            $info["community_name"]=(new roominfoService())->communityName($info['community_id']);
            View::assign('info',$info);
            
            return View::fetch('car_edit');
        }else{
            //获取表单数据
            $data = request()->post();
            $data = array_filter($data);
            //var_dump($data);die;
           
            
            $result =Db::table("carspace")->update($data);
            //判断数据是否插入成功
            if($result){
                return "修改信息成功";
                $this->success('修改信息成功',url('carlist'));
            }else{
                $this->error('修改信息失败',url('carEdit'));
            }
        }
    }
    public function carDelId(){
        $id=request()->get("id");
        $result = (new roominfoService())->deleteRoomInfo($id);

        if($result){
            $url=url('carList');
		    echo "<script>alert('删除成功');location.href='$url'</script>";
		    die;
            $this->success("删除房屋成功");
        }else{
            $this->error("删除房屋失败");
        }

    }
    
    public function carDel(){
       
        $id = explode(',',request()->param('id'));
        $carlist=Db::name('carspace')->where('id','in',$id)->select()->toArray();
       
        if (count($carlist) != count($id)) {
            return json(['error' => '房屋信息不存在']);
        }
        
        //未同步的房屋删除
        foreach($carlist as $inf){
            $result = Db::table("carspace")->where("id",$inf["id"])->delete();
            if(empty($result)){
                return json(['error' => '房屋删除失败']); 
            }
        }
            return json(['info' => '删除成功']);
        
      
       
    }
    
    //通过Excel批量添加房屋信息 
    public function carExcel(){
        if(request()->isPOST()){
            //上传excel文件
            $file = request()->file('myfile');
            //移到/public/excel/下
            $info = $file->move(ROOT_PATH.'public'.DS.'excel');
            //上传文件成功
            if ($info) {
                //引入PHPExcel类
                vendor('PHPExcel.PHPExcel.Reader.Excel2007');
                //获取上传后的文件名
                $fileName = $info->getSaveName();
                //文件路径
                $filePath = dir(getcwd())->path.'/excel/'.$fileName;
                //判断文件格式，实例化相应的PHPExcel类，读取excel文件
                $extension = strtolower( pathinfo($fileName, PATHINFO_EXTENSION));
                if ($extension =='xlsx' ) {
                    $objReader = new \PHPExcel_Reader_Excel2007();
                    $objPHPExcel = $objReader ->load($filePath);
                } else if ($extension=='xls'){
                    return "格式xlsx";
                    $objReader = new \PHPExcel_Reader_Excel5(); 
                    $objPHPExcel = $objReader ->load($filePath);
                }else if ($extension=='csv') {
                    $objReader = new \PHPExcel_Reader_CSV();
                    //默认输入字符集
                    $objReader->setInputEncoding('GBK');
                    //默认的分隔符
                    $objReader->setDelimiter(',');
                    //载入文件
                    $objPHPExcel = $objReader ->load($filePath);
                }else{
                    $this->success('文件格式错误',url('carExcel'));
                }  
                //读取excel文件中的第一个工作表
                $sheet = $objPHPExcel->getSheet(0);
                $allRow = $sheet->getHighestRow();  //取得总行数
                //$allColumn = $sheet->getHighestColumn();  //取得总列数
                //从第三行开始插入，第一行是列名
                for ($j=2; $j <= $allRow; $j++) {
                    $communityName = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//小区名称
                    if(isset($communityName)){
                        $communityList = (new roominfoService())->communityNameId($communityName);
                        if(isset($communityList)){
                            $data['community_id'] = $communityList['community_id'];  
                        }else{
                            $data['community_id'] = '';
                        }  
                    }else{
                        $data['community_id'] = '';
                    }
                    $data['group'] = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//组团
                    $data['building'] = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//楼栋
                    $data['unit'] = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();//单元
                    $data['room'] = $objPHPExcel->getActiveSheet()->getCell("E".$j)->getValue();//房号
                    $data['address'] = $data['group']."-".$data['building']."-".$data['unit']."-".$data['room'];
                    $data['owner_name'] = $objPHPExcel->getActiveSheet()->getCell("F".$j)->getValue();//业主姓名
                    $data['owner_phone'] = $objPHPExcel->getActiveSheet()->getCell("G".$j)->getValue();//业主电话
                    $data['parkspace'] = $objPHPExcel->getActiveSheet()->getCell("H".$j)->getValue();//车位号
                    $data['car_number'] = $objPHPExcel->getActiveSheet()->getCell("I".$j)->getValue();//单价
                    $data['price'] = $objPHPExcel->getActiveSheet()->getCell("J".$j)->getValue();//费用
                    $status = $objPHPExcel->getActiveSheet()->getCell("K".$j)->getValue();
                    $data['status']="";
                    if($status=="自用"){
                        $data['status']=1;
                    }
                    if($status=="闲置"){
                        $data['status']=2;
                    }
                    if($status=="已租"){
                        $data['status']=3;
                    }
                    //租赁方车牌
                    $data['lease_car_number'] =$objPHPExcel->getActiveSheet()->getCell("L".$j)->getValue();
                    if(empty($data['lease_car_number'])){
                        $data['lease_car_number'] = ''; 
                    }
                     //租赁方姓名
                    $data['lease_name'] =$objPHPExcel->getActiveSheet()->getCell("M".$j)->getValue();
                    if(empty($data['lease_name'])){
                        $data['lease_name'] = ''; 
                    }
                    //租赁方电话
                    $data['lease_phone'] =$objPHPExcel->getActiveSheet()->getCell("N".$j)->getValue();
                    if(empty($data['lease_phone'])){
                        $data['lease_phone'] = ''; 
                    }
                    $data['time'] = date('Y-m-d H:i:s',time());//添加时间

                    $data = array_filter($data);
                    $number = count($data);
                    $numbers = 12;
                    if( $number >= $numbers){
                        $last_id = Db::name('carspace')->insertGetId($data);; 
                        //判断数据是否插入成功
                        if ($last_id) {
                            echo "第".$j."行导入成功，车位表第:".$j."条！<br/>";
                        }else{
                            echo "第".$j."行导入失败！<br/>";
                        } 
                        
                    }else{
                        echo "第".$j."行数据不完整，导入失败！<br/>";
                    }
                }
            }else{
                $this->success('上传文件失败',url('carExcel'));
            }
        }else{
            return View::fetch('car_excel');
        }
    }

    //导出房屋到Excel
    public function carExportExcel(){
        //获取账单数据
        $id = request()->param('id');
        $export = request()->param('export');
        $export = str_replace("|","\"",$export);
        if(!empty($id)){
            $id = explode(',',request()->param('id'));
            $carlist = Db::name('carspace')->where('id','in',$id)->select()->toArray();;
            if(count($carlist) != count($id)){
                return json(['error' => '车位信息不完整']);
            }
        }else{
            //查询小区信息
            $com = $this->pidTokenId();
            $whe['community_id'] = array('in',$com['community_id']);
            $communitylist = (new roominfoService())->communityList($whe);
            $community_id = $com['community_id'];
            $where = json_decode($export,true);
            
            $carlist=Db::name('carspace')->where('community_id','in',$community_id)->where($where)->order('id desc')->select()->toArray();
            if(empty($carlist)){
                return json(['error' => '没有数据']);
            }
        }
        
        //设置表头
        //引入PHPExcel类
        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
        $objPHPExcel = new \PHPExcel();
        //设置表头
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '小区名称')
        ->setCellValue('B1', '组团')
        ->setCellValue('C1', '楼栋')
        ->setCellValue('D1', '单元')
        ->setCellValue('E1', '房号')
        ->setCellValue('F1', '完整门牌号')
        ->setCellValue('G1', '业主姓名')
        ->setCellValue('H1', '业主电话')
        ->setCellValue('I1', '车位号')
        ->setCellValue('J1', '车牌号')
        ->setCellValue('K1', '车位费用')
        ->setCellValue('L1', '状态')
        ->setCellValue('M1', '租赁方车牌')
        ->setCellValue('N1', '租赁方姓名')
        ->setCellValue('O1', '租赁方电话');

        $count = count($carlist);  //计算有多少条数据
        for ($i=2; $i <= $count+1; $i++) {
            //根据小区ID查询小区名称
            $commId = $carlist[$i-2]["community_id"];
            $communityName = (new roominfoService())->communityIdName($commId);
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $communityName['community_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $carlist[$i-2]["group"]);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $carlist[$i-2]["building"]);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $carlist[$i-2]["unit"]);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $carlist[$i-2]["room"]);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $carlist[$i-2]["address"]);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $carlist[$i-2]["owner_name"]);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $carlist[$i-2]["owner_phone"]);
            $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $carlist[$i-2]["parkspace"]);
            $objPHPExcel->getActiveSheet()->setCellValue('J' . $i, $carlist[$i-2]["car_number"]);
            $objPHPExcel->getActiveSheet()->setCellValue('K' . $i, $carlist[$i-2]["price"]); 
           
            $status="";
            if($carlist[$i-2]["status"] == 1){
                $status = '自用';
            }elseif($carlist[$i-2]["status"] == 2){
                $status = '闲置';
            }elseif($carlist[$i-2]["status"] == 3){
                $status = '已租';
            }
            $objPHPExcel->getActiveSheet()->setCellValue('L' . $i, $status);
            $objPHPExcel->getActiveSheet()->setCellValue('M' . $i, $carlist[$i-2]["lease_car_number"]);
            $objPHPExcel->getActiveSheet()->setCellValue('N' . $i, $carlist[$i-2]["lease_name"]);
            $objPHPExcel->getActiveSheet()->setCellValue('O' . $i, $carlist[$i-2]["lease_phone"]);
            
        }
        $objPHPExcel->getActiveSheet()->setTitle('车位信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");
        header('Content-Disposition: attachment;filename="车位信息.xls"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }
    
    
    
    public function object_to_array($obj){
        $_arr = is_object($obj) ? get_object_vars($obj) :$obj;
        foreach($_arr as $key=>$val){
            //if($key !== 'gioouts'){
                $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
                $arr[$key] = $val;
           // }
        }
        return $arr;
    }
    
    public function getgroup(){
		$community_id = request()->param('community_id');
        $communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["community_id"];
        $group = (new xcxService())->groupList($community_id);  
        
        sort($group ,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
    
        return $group ;
	}
    
	public function getbuilding(){
		$community_id = request()->param('community_id');
		
        $communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["community_id"];
        $group = request()->param('group');;
        $building = (new xcxService())->buildingList($group,$community_id);
        sort($building,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $building;
	}
	public function getunit(){
		$community_id = request()->param('community_id');
		$communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["community_id"];
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = (new xcxService())->unitList($building,$group,$community_id);
        //Log::write($group,"2343");
        sort($unit,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $unit;
	}
	public function getroom(){
		$community_id = request()->param('community_id');
		$communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["community_id"];
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = request()->param('unit');
        $room = (new xcxService())->roomList($unit,$building,$group,$community_id);
        sort($room,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $room;
	}
}